package com.guc.coroutines.db

import android.content.Context
import java.io.*
import kotlin.concurrent.thread

/**
 * Created by guc on 2021/3/23.
 * Description：图片缓存工具
 */
object ImageCacheUtil {
    private lateinit var cacheDao: CacheDao
    private lateinit var context:Context
    private const val TAG = "ImageCacheUtil"

    fun getCacheDao()= MyDataBase.getInstance(context.applicationContext).fileCacheDao()
    fun init(context: Context) {
        thread {
            this.context = context
            val filePath =
                (context.externalCacheDir?.absolutePath
                    ?: context.cacheDir.absolutePath) + "/images/"
            val file = File(filePath)
            createFile(file, true)
        }
    }
    private fun createFile(file: File, isDir: Boolean) {
        if (file.isDirectory || isDir) {
            file.mkdirs()
        } else {
            file.parentFile?.mkdirs()
            if (!file.exists()) {
                file.createNewFile()
            }
        }
    }

    /**
     * 读取文件中内容
     */
    private fun readFile2String(file: String, context: Context ): String {
        return try {
            val content = StringBuilder()
            val output = FileInputStream(file)
            val reader = BufferedReader(InputStreamReader(output))
            reader.use {//kotlin内置的扩展函数，保证lambda表达式中代码执行完毕后自动关闭外层的数据流
                reader.forEachLine {
                    content.append(it)
                }
            }
            content.toString()
        } catch (e: IOException) {
            e.printStackTrace()
            "IOException"
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            "FileNotFoundException"
        }
    }


    private fun hasInit() = ImageCacheUtil::cacheDao.isInitialized

    interface ImageDataCallback {
        fun callback(base64: String)
    }
}